package com.daiyang.lottery.controller;

import com.daiyang.lottery.common.errorcode.ControllerErrorCodeConstants;
import com.daiyang.lottery.common.exception.ControllerException;
import com.daiyang.lottery.common.pojo.CommonResult;
import com.daiyang.lottery.common.util.JacksonUtil;
import com.daiyang.lottery.controller.param.CreateActivityParam;
import com.daiyang.lottery.controller.param.PageListParam;
import com.daiyang.lottery.controller.result.CreateActivityResult;
import com.daiyang.lottery.controller.result.GetActivityDetialResult;
import com.daiyang.lottery.controller.result.FindActivityListResult;
import com.daiyang.lottery.service.ActivityService;
import com.daiyang.lottery.service.dto.ActivityDTO;
import com.daiyang.lottery.service.dto.ActivityDetailDTO;
import com.daiyang.lottery.service.dto.CreateActivityDTO;
import com.daiyang.lottery.service.dto.PageListDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.stream.Collectors;

@RestController
public class ActivityController {
    private static final Logger logger = LoggerFactory.getLogger(ActivityController.class);

    @Autowired
    private ActivityService activityService;

    @RequestMapping("/activity/create")
    public CommonResult<CreateActivityResult> createActivity
            (@Validated @RequestBody  CreateActivityParam param){
            logger.info("CreateActivityParam Createactivityparam: {}", JacksonUtil.writeValueAsString(param));
            CreateActivityDTO createActivityDTO = activityService.createActivity(param);
            return CommonResult.success(convertToCreateActivityResult(createActivityDTO));
    }

    @RequestMapping("/activity/find-list")
    public CommonResult<FindActivityListResult> findActivityList(PageListParam param) {
        logger.info("FindActivityListParam findActivityListParam: {}"
                , JacksonUtil.writeValueAsString(param));
        PageListDTO<ActivityDTO> findActivityListDTO
                =activityService.findActivityList(param);

       return CommonResult.success(convertToFindActivityListResult(findActivityListDTO));
    }
    @RequestMapping("/activity-detail/find")
    public CommonResult<GetActivityDetialResult> getActivityDetail(Long activityId) {
       logger.info("FindActivityDetial findActivityDetialParam: {}"
               , activityId);
       ActivityDetailDTO activityDetailDTO = activityService.getActivityDetail(activityId);
       return CommonResult.success(
               convertToGetActivityResult
                       (activityDetailDTO));

    }

    private GetActivityDetialResult convertToGetActivityResult(ActivityDetailDTO activityDetailDTO) {
        logger.info("convertToGetActivityResult activityDetailDTO: {}", JacksonUtil.writeValueAsString(activityDetailDTO));
        if(null==activityDetailDTO){
            throw new ControllerException(ControllerErrorCodeConstants.GET_ACTIVITY_DETAIL_ERROR);
        }
        GetActivityDetialResult result = new GetActivityDetialResult();
        result.setActivityId(activityDetailDTO.getActivityId());
        result.setActivityName(activityDetailDTO.getActivityName());
        result.setDescription(activityDetailDTO.getDesc());
        result.setValid(activityDetailDTO.valid());
        // 抽奖顺序：一等奖、二等奖、三等奖
        result.setPrizes(activityDetailDTO.getPrizeDTOList().stream()
                .sorted(Comparator.comparingInt(prizeDTO->prizeDTO.getTiers().getCode()))
                .map(prizeDTO -> {
                    GetActivityDetialResult.Prize prize = new GetActivityDetialResult.Prize();
                    prize.setPrizeId(prizeDTO.getPrizeid());
                    prize.setName(prizeDTO.getName());
                    prize.setDescription(prizeDTO.getDescription());
                    prize.setPrizeTierName(prizeDTO.getTiers().getMessage());
                    prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                    prize.setImageUrl(prizeDTO.getImageUrl());
                    prize.setValid(prizeDTO.valid());
                    prize.setPrice(prizeDTO.getPrice());
                    return prize;
                }).collect(Collectors.toList())
        );

        // 人员信息
        result.setUsers(activityDetailDTO.getUserDTOList().stream()
                .map(UserDTO -> {
                    GetActivityDetialResult.User user = new GetActivityDetialResult.User();
                    user.setUserId(UserDTO.getUserId());
                    user.setUserName(UserDTO.getUserName());
                    user.setValid(UserDTO.valid());
                    return user;
                }).collect(Collectors.toList())
        );
        return result;


    }

    private FindActivityListResult convertToFindActivityListResult(PageListDTO<ActivityDTO> findActivityListDTO) {
        if(null == findActivityListDTO){
            throw new ControllerException(ControllerErrorCodeConstants.ACTIVITY_NOT_FIND_ERROE);
        }
        FindActivityListResult result = new FindActivityListResult();
        result.setTotal(findActivityListDTO.getTotal());
        result.setRecords(findActivityListDTO.getRecords()
                .stream()
                .map(dto->{
                            FindActivityListResult.ActivityInfo activityInfo =
                                    new FindActivityListResult.ActivityInfo();
                            activityInfo.setActivityId(dto.getActivityId());
                            activityInfo.setActivityName(dto.getActivityName());
                            activityInfo.setDescription(dto.getDescription());
                            activityInfo.setValid(dto.valid());
                            return activityInfo;
                        }).collect(Collectors.toList()));
            return result;
    }

    private CreateActivityResult convertToCreateActivityResult(CreateActivityDTO createActivityDTO) {
        if(null == createActivityDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.CREATE_ACTIVITY_ERROR);
        }
        CreateActivityResult result = new CreateActivityResult();
        result.setActivityId(createActivityDTO.getActivityId());
        return result;
    }
}
